#客户端
# 创建套接字
import socket
import sys
import json
import threading
import traceback


class MessageRecetiver(threading.Thread):
    def __init__(self,c_sock):
        threading.Thread.__init__(self)
        self.sock = c_sock
        self.setDaemon(True)
    def run(self):
        while True:
            data = self.sock.recv(4096)
            if data is None or len(data) == 0:
                break
            data = data.decode("utf-8")
            data = json.loads(data)
            if data["command"] == "message":
                from_username_ = data["from"]
                to_ = data["to"]
                message_ = data["message"]
                print("{}said to{} {}".format(from_username_,to_,message_))

def regiter_myself(sock,username):
    sock.send(json.dumps({"command":"regiter",
                          "username":username,
                          }).encode("utf-8"))
# 服务器
if len(sys.argv) <= 3:
    print("usage:{}address port".format(sys.argv[0]))
    sys.exit(-1)
# address = "127.0.0.1"
# port = 3000
address = sys.argv[1]
port = int(sys.argv[2])
username = sys.argv[3]
# 创建套接字对象
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM,0)
# 连接到指定地址与端口(connect)
sock.connect((address,port))
# 调用注册
regiter_myself(sock,username)
MessageRecetiver(sock).start()
while True:
   try:
       user = input("user:")
       message = input("message:")
       sock.send(json.dumps({"command":"message",
                             "to":user.strip(),
                             "from":username,
                             "message":message.strip()}).encode("utf-8"))
       # 读写数据
       # data = input("请输入data:")
       # print("data"+data)
       # sock.send(bytes(data.encode("utf-8")))
       # data = sock.recv(1000)
       # # 关闭套接字对象
       # sock.close()
   #   返回值异常
   except Exception as e:
       traceback.print_exc()
   #  监听键盘异常
   except KeyboardInterrupt:
       break
sock.close()